import { fetchStoredToken } from "../../utils/token";
const app = getApp();
Page({
  data: {
    avatarUrl: app.globalData.defaultAvatarUrl,
  },
  onChooseAvatar(event) {
    const { avatarUrl } = event.detail;
    this.setData({
      avatarUrl,
    });
  },
  submitUserInfo(event) {
    const token = fetchStoredToken();
    const { baseURL } = app.globalData;
    if (!token) {
      wx.showToast({
        title: "未授权",
        icon: "error",
      });
      return;
    }
    wx.uploadFile({
      filePath: this.data.avatarUrl,
      header: {
        Authorization: `Bearer ${token}`,
      },
      name: "avatar",
      url: `${baseURL}/upload`,
      formData: {
        nickname: event.detail.value.nickname,
      },
      fail: (err) => {
        console.error("上传失败:", err);
        wx.showToast({
          title: "上传失败",
          icon: "error",
        });
      },
      success: (res) => {
        try {
          const { nickname, avatar } = JSON.parse(res.data);
          wx.setStorageSync("user", { nickname, avatar });
          wx.switchTab({
            url: "/pages/profile/profile",
            success() {
              const pages = getCurrentPages();
              const currentPage = pages[pages.length - 1];
              currentPage.onLoad();
            },
          });
        } catch (error) {
          console.error("解析响应失败:", error);
          wx.showToast({
            title: "解析响应失败",
            icon: "error",
          });
        }
      },
    });
  },
});
